package com.sws.weixin.service.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sws.weixin.entity.TemplateInfo;
import com.sws.weixin.mapper.Template2Mapper;
import com.sws.weixin.service.TemplateService;
import com.sws.weixin.token.TokenUtil;
import com.sws.weixin.util.HttpUtil;
import com.sws.wxtemplate.domain.WechatTemplate;
import com.sws.wxtemplate.mapper.WechatTemplateMapper;
import com.sws.wxtemplate.service.IWechatTemplateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;


@Service
public class TemplateServiceImpl implements TemplateService {


    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private Template2Mapper templateMapper;
    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private IWechatTemplateService wechatTemplateService;

    @Autowired
    private WechatTemplateMapper wechatTemplateMapper;
    @Autowired
    private  TokenUtil tokenUtil;
    /**
     * 获取存储模板
     */
    public void fetchAndSaveTemplates() {
        try {
            System.out.println("restTemplate 是否注入: " + (restTemplate != null));
            System.out.println("templateMapper 是否注入: " + (templateMapper != null));
            // 1. 获取 AccessToken
            String accessToken = tokenUtil.getAccessToken();
            String url = "https://api.weixin.qq.com/cgi-bin/template/get_all_private_template?access_token=" + accessToken;

            // 2. 调用微信 API
            String jsonResponse = HttpUtil.doGet(url);
            System.out.println(jsonResponse);
            if (jsonResponse == null) {
                throw new RuntimeException("微信API未返回数据");
            }

            // 3. 解析 JSON 并处理错误
            JsonNode root = objectMapper.readTree(jsonResponse);
            if (root.has("errcode") && root.get("errcode").asInt() != 0) {
                throw new RuntimeException("微信API错误: " + root.get("errcode") + " - " + root.get("errmsg"));
            }

            // 4. 提取模板列表并存储
            JsonNode templateList = root.get("template_list");
            if (templateList != null && templateList.isArray()) {
                for (JsonNode templateNode : templateList) {
                    TemplateInfo template = objectMapper.treeToValue(templateNode, TemplateInfo.class);

                    String targetJson = template.generateContentJson(); // 生成目标 JSON
                    System.out.println("原有json格式数据如下：" + template.getContent());
                    System.out.println("输出对应的json格式数据如下:"+ targetJson); // 输出或存储到数据库

                    // 把查询到的微信消息模板数据，转换为  WechatTemplate 对象，进行存储
                    WechatTemplate wechatTemplate = new WechatTemplate();
                    wechatTemplate.setStatus("0");
                    wechatTemplate.setTemplateId(template.getTemplateId());
                    wechatTemplate.setContent(targetJson);
                    wechatTemplate.setName(template.getTitle());

                    WechatTemplate flag = templateMapper.selectByWxTemplateId(template.getTemplateId());
                    if(flag == null){
                        wechatTemplateService.insertWechatTemplate(wechatTemplate);
                    }




                    templateMapper.insertOrUpdate(template);  // 调用 Mapper 方法
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void deleteTemplate(String templateId) throws Exception {
        try {
            // 1. 获取 AccessToken
            String accessToken = tokenUtil.getAccessToken();
            String url = "https://api.weixin.qq.com/cgi-bin/template/del_private_template?access_token=" + accessToken;

            // 2. 构建请求体
            Map<String, String> requestBody = new HashMap<>();
            requestBody.put("template_id", templateId);

            // 3. 发送 POST 请求
            ResponseEntity<String> response = restTemplate.postForEntity(
                    url,
                    requestBody,
                    String.class
            );

            // 4. 处理响应
            String jsonResponse = response.getBody();
            JsonNode root = objectMapper.readTree(jsonResponse);

            if (root.has("errcode") && root.get("errcode").asInt() != 0) {
                throw new RuntimeException("微信API错误: " + root.get("errcode") + " - " + root.get("errmsg"));
            }

            // 5. 删除本地数据库记录（根据业务需求决定是否需要）
            templateMapper.deleteByTemplateId(templateId);

        } catch (HttpClientErrorException e) {
            // 处理 HTTP 4xx/5xx 错误
            throw new RuntimeException("HTTP请求失败: " + e.getStatusCode() + " - " + e.getResponseBodyAsString());
        } catch (Exception e) {
            throw new RuntimeException("删除模板失败: " + e.getMessage());
        }
    }

    /**
     * 删除模版中的所有消息，用于同步信息
     */
    @Override
    public void deleteTemplatAll() {
        templateMapper.deleteTemplatAll();
        wechatTemplateMapper.deleteWechatTemplateAll();
    }

}